﻿
(function ($) {
    //https://code.google.com/apis/console/?pli=1#project:642695389602:access
    var _credentialsKey = "AIzaSyCoH - ixltepX8jJoYE4DiYU60YpulQOwGQ"; //http://localhost 
    //var _credentialsKey = "AIzaSyCBsfCsTgIdo7Rwt_1cIwz2YXI8h - gPCbQ"; //http://my_registered_server_name
    var panorama = {
        p: null,
        marker: null,
        infowindow: null,
        map: null,
        unset: function () {
            if (this.p) {
                this.p.unbind("position");
                this.p.setVisible(false);
            }
            this.p = null;
            this.marker = null;
        },
        setMap: function (map) {
            this.map = map;
        },
        setMarker: function (marker) {
            this.marker = marker;
        },
        setInfowindow: function (infowindow) {
            this.infowindow = infowindow;
        },
        open: function () {
            //this.infowindow.open(this.map, this.marker);
        },
        run: function (id) {
            if (!this.marker) return;
            this.p = new google.maps.StreetViewPanorama(document.getElementById(id), {
                navigationControl: true,
                navigationControlOptions: { style: google.maps.NavigationControlStyle.ANDROID },
                enableCloseButton: false,
                addressControl: false,
                linksControl: false
            });
            this.p.bindTo("position", this.marker);
            this.p.setVisible(true);
        }
    }

    $.widget("msls.lightswitchGoogleMapsControl", {
        options: {
            //var centerPosition = new google.maps.LatLng(parseFloat(screen.Place.Latitude), parseFloat(screen.Place.Longitude));
            //center: centerPosition,
            zoom: 16,
            disableDefaultUI: true,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            mapTypeControl: true,
            mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.DROPDOWN_MENU }, //DEFAULT, DROPDOWN_MENU, HORIZONTAL_BAR
            navigationControl: false,
            zoomControl: true,
            //navigationControlOptions: { position: google.maps.ControlPosition.RIGHT, style: google.maps.NavigationControlStyle.DEFAULT },
            scrollwheel: true,
            panControl: false,
            streetViewControl: false

        },

        _create: function () {
        },

        _init: function () {
            this.createMap();
        },

        destroy: function () {
            this._destroyGoogleMapsControl();
        },

        createMap: function () {
            var mapOptions = this.options;
            this.map = new google.maps.Map(this.element[0], mapOptions);
            //this.map.overlayMapTypes.push(null); //???
            //This function destroys a google map.Always destroy a map before emptying or removing its div !
            //$map.gmap3({
            //    map: {
            //        action: 'destroy'
            //    }
            //});
            //$('#gmap', $(element)).remove();

            //if ($map == null || ($map != null && $map.gmap == null)) {
            //    $(element).append('<div id="gmap_canvas" class="gmap3" style="width: 100%; height: 100%"></div>');
            //}
            //else {
            //    $map.gmap('clear', 'markers');
            //}
            //$map.css({ 'width': '630px', 'height': '400px' });

        },

        resetMap: function () {
            //this.map.entities.clear();
            //this.map.setView({ zoom: this.options.zoom, center: location })
        },
        getCenter: function (callback) {
            if (callback && typeof (callback) === "function") {
                callback(this.map.getCenter());
            }
        },
        setCenter: function (place) {
            var centerPosition = new google.maps.LatLng(parseFloat(place.Latitude), parseFloat(place.Longitude));
            this.map.setCenter(centerPosition);
        },

        getCurrentPosition: function (place) {
            var widgetInstance = this;
            //this.htmlMapElement = this.element[0];
            var centerPosition = new google.maps.LatLng(parseFloat(place.Latitude), parseFloat(place.Longitude));
            //var $map = this.htmlMapElement;//$('#gmap_canvas', $(element));
            ////gmap3 sample
            //$map.width("100%").height("100%").gmap3({
            //    map: {
            //        //action: 'init',
            //        address: "Adelaide, SA, Australia",
            //        options: {
            //            center: centerPosition,
            //            zoom: 16,
            //            disableDasefaultUI: true,
            //            mapTypeId: google.maps.MapTypeId.ROADMAP,
            //            mapTypeControl: true,
            //            mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.DROPDOWN_MENU },
            //            navigationControl: false,
            //            scrollwheel: true,
            //            panControl: false,
            //            streetViewControl: true
            //        }
            //    }
            //    //,trigger: "resize"
            //});
            var map = this.map;

            var geocoder = new google.maps.Geocoder();
            if (!place.Latitude || !place.Longitude) {
                if (navigator && navigator.geolocation) {
                    navigator.geolocation.getCurrentPosition(geo_success);
                } else {
                    alert("Error. No Gps signal");
                    function geo_success(position) {
                        centerPosition = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                        place.Latitude = position.coords.latitude;
                        place.Longitude = position.coords.longitude;
                        widgetInstance._setMarkerPosition(centerPosition, place, geocoder, (place.Draggable == null || place.Draggable == true));
                        if (!place.Latitude) {
                            geocoder.geocode({ 'latLng': centerPosition }, function (results, status) {
                                if (status == google.maps.GeocoderStatus.OK) {
                                    if (results[0]) {
                                        place.Address = results[0].formatted_address;
                                    };
                                }
                            });
                        }
                    }
                }
            }
            else {
                widgetInstance._setMarkerPosition(centerPosition, place, geocoder, (place.Draggable == null || place.Draggable == true));
            }
        },

        getStaticPositions: function (places, callback) {
            //this.map.clearOverlays();
            //this.map.entities.clear();
            google.maps.Map.prototype.clearMarkers = function () {
                for (var i = 0; i < this.markers.length; i++) {
                    this.markers[i].setMap(null);
                }
                this.markers = new Array();
            };
            var geocoder = new google.maps.Geocoder();
            var widgetInstance = this;
            $.each(places, function (index, place) {
                if (place.Latitude != null && place.Longitude != null) {
                    centerPosition = new google.maps.LatLng(place.Latitude, place.Longitude);
                    var marker = widgetInstance._setMarkerPosition(centerPosition, place, geocoder, false);
                    google.maps.event.clearListeners(marker, 'click');
                    google.maps.event.addListener(marker, 'click', function () {
                        if (callback && typeof (callback) === "function") {
                            callback(place.Id);
                        }
                    });
                }
            });
        },

        getPositionByAddress: function (place) {
            var geocoder = new google.maps.Geocoder();
            geocoder.geocode({ 'address': place.Address }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    if (results[0]) {
                        var centerPosition = results[0].geometry.location;
                        place.Latitude = centerPosition.lat();
                        place.Longitude = centerPosition.lng();
                        //widgetInstance._setMarkerPosition(centerPosition, place, geocoder, true);
                    };
                }
            });
        },

        _setMarkerPosition: function (markerPosition, place, geocoder, isDraggable) {
            var map = this.map;
            //map.clearOverlays();
            google.maps.event.trigger(map, "resize");
            var centerPosition = new google.maps.LatLng(markerPosition.lat() + 0.002, markerPosition.lng()- 0.002); // - 0.05
            map.setCenter(centerPosition);
            var marker = new google.maps.Marker({
                //title: place.Address,
                draggable: isDraggable,
                //clickable: true,
                animation: google.maps.Animation.DROP, //DROP|BOUNCE
                icon: "http://maps.google.com/mapfiles/marker_green.png",
                position: markerPosition,
                map: map,
            });
            if (isDraggable)
            {
                google.maps.event.addListener(marker, 'dragend', function () {
                    var position = marker.getPosition();
                    place.Latitude = position.lat();
                    place.Longitude = position.lng();
                    geocoder.geocode({ 'latLng': position }, function (results, status) {
                        if (status == google.maps.GeocoderStatus.OK) {
                            if (results[0]) {
                                place.Address = results[0].formatted_address;
                            };
                        }
                    });

                });
            }

            var infowindow = new google.maps.InfoWindow({
                content: '<div id="infocontent" style="width:300px;height:200px;"></div>'
            });
            panorama.setMarker(marker);
            panorama.setInfowindow(infowindow);
            google.maps.event.addListener(infowindow, 'domready', function () {
                panorama.run('infocontent');
            });
            //google.maps.event.addListener(infowindow, 'closeclick', function () {
            //    panorama.unset();
            //});
            google.maps.event.addListener(marker, 'click', function () {
                infowindow.open(map, marker);
                //panorama.open();
            });
            return marker;
        },

        createMovementRoute: function (fromPlace, toPlace, drivingMode, trafficMode) {
            if (!this.directionsService) {
                this.directionsService = new google.maps.DirectionsService();
                this.directionsDisplay = new google.maps.DirectionsRenderer({ suppressInfoWindows: true });
            }
            var directionsService = this.directionsService;
            var directionsDisplay = this.directionsDisplay;
            directionsDisplay.setMap(this.map);
            var panel = document.getElementById("directionsItinerary");
            panel.innerHTML = "";
            directionsDisplay.setPanel(panel);
            var geocoder = new google.maps.Geocoder();
            //var widgetInstance = this;
            //if (!fromPlace.Latitude || !fromPlace.Longitude)
            //    widgetInstance.getCurrentPosition(fromPlace);
            //if (!toPlace.Latitude || !toPlace.Longitude)
            //    widgetInstance.getCurrentPosition(toPlace);
            var fromPoint = new google.maps.LatLng(parseFloat(fromPlace.Latitude), parseFloat(fromPlace.Longitude));
            var toPoint = new google.maps.LatLng(parseFloat(toPlace.Latitude), parseFloat(toPlace.Longitude));
            var request = {
                origin: fromPoint,
                destination: toPoint,
                travelMode: ((drivingMode) && (drivingMode === true) ? google.maps.DirectionsTravelMode.WALKING : google.maps.DirectionsTravelMode.DRIVING), //Pode ser Walking, Driving ou Bicycling
                optimizeWaypoints: true
            };

            var zoom = this.options.zoom;
            var map = this.map;
            directionsService.route(request, function (response, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                    map.setZoom(zoom);
                    map.setCenter(fromPoint);
                    directionsDisplay.setDirections(response);
                }
            });

            if ((trafficMode != null) && (trafficMode === true)) {
                if (!this.trafficLayer)
                    this.trafficLayer = new google.maps.TrafficLayer(); 

                if (this.trafficLayer) {
                    this.trafficLayer.setMap(this.map);
                }
            }
            else if ((trafficMode != null) && (trafficMode === false) && (this.trafficLayer)) {
                this.trafficLayer.setMap();
            }
            //this.map.overlayMapTypes.push(null); //???
        },

        _handleError: function (error) {
            alert("An error occurred.  " + error.message);
        },

        _destroyGoogleMapsControl: function () {
            panorama.unset();
            if (this.map != null) {
                //this.map.dispose();
                this.map = null;
            }
        }
    });
}(jQuery));
